<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Form, Field, Button, CellGroup, Pagination, Empty, Dialog, ActionSheet, showToast, showSuccessToast, showFailToast } from 'vant'
import { ordersApi, type Order, type OrderItem } from '../api/orders'
import { productsApi, type Product } from '../api/products'

type OrderItemForm = { productId?: number; quantity: number }
type OrderListItem = { ID: number; customer: string; responsible?: string; total_price: number; items?: OrderItem[]; CreatedAt?: string }

// 创建订单表单
const products = ref<Product[]>([])
const customer = ref('')
const responsible = ref('')
const items = ref<OrderItemForm[]>([{ productId: undefined, quantity: 1 }])

const findProduct = (id?: number) => products.value.find(p => p.ID === id)
const detailedItems = computed(() => items.value.map((it: OrderItemForm) => {
  const p = findProduct(it.productId)
  return {
    productId: it.productId,
    name: p?.name ?? '',
    price: p?.price ?? 0,
    quantity: it.quantity,
    amount: (p?.price ?? 0) * (it.quantity || 0)
  }
}))
const totalPrice = computed(() => detailedItems.value.reduce((s: number, it: any) => s + it.amount, 0))

function addRow() { items.value.push({ productId: undefined, quantity: 1 }) }
function removeRow(idx: number) { if (items.value.length > 1) items.value.splice(idx, 1) }

async function loadProducts() {
  try {
    const { data } = await productsApi.getList()
    products.value = data
  } catch (e: any) {
    const msg = e?.response?.data?.error || e?.message || '加载产品失败'
    showFailToast(msg)
  }
}

async function submitOrder() {
  console.log('=== submitOrder开始执行 ===')
  console.log('当前客户:', customer.value)
  console.log('当前负责人:', responsible.value)
  console.log('当前商品项:', items.value)
  
  // 验证客户名称
  if (!customer.value || customer.value.trim() === '') { 
    console.log('客户名称验证失败')
    showFailToast('请填写客户名称'); 
    return 
  }
  
  // 验证负责人
  if (!responsible.value || responsible.value.trim() === '') { 
    console.log('负责人验证失败')
    showFailToast('请填写负责人'); 
    return 
  }
  
  // 验证商品选择
  if (items.value.length === 0) {
    console.log('商品数量验证失败')
    showFailToast('请至少添加一个商品')
    return
  }
  
  // 验证每个商品项
  for (let i = 0; i < items.value.length; i++) {
    const item = items.value[i]
    console.log(`验证第${i + 1}行商品:`, item)
    if (!item.productId) {
      console.log(`第${i + 1}行商品ID验证失败`)
      showFailToast(`第${i + 1}行请选择商品`)
      return
    }
    if (!item.quantity || item.quantity <= 0) {
      console.log(`第${i + 1}行数量验证失败`)
      showFailToast(`第${i + 1}行请填写有效数量`)
      return
    }
  }
  
  const payload = {
    customer: customer.value.trim(),
    responsible: responsible.value.trim(),
    total_price: Number(totalPrice.value.toFixed(2)),
    items: items.value.map((it: OrderItemForm) => {
      const p = findProduct(it.productId)
      return { 
        product_id: it.productId!, 
        product_name: p?.name ?? '', 
        quantity: it.quantity, 
        price: p?.price ?? 0 
      }
    })
  }
  
  console.log('=== 准备提交订单 ===')
  console.log('请求载荷:', JSON.stringify(payload, null, 2))
  
  try {
    console.log('开始发送HTTP请求...')
    const response = await ordersApi.create(payload)
    console.log('HTTP请求成功:', response)
    showSuccessToast('订单已创建')
    customer.value = ''
    responsible.value = ''
    items.value = [{ productId: undefined, quantity: 1 }]
    await loadOrders()
    console.log('=== submitOrder执行完成 ===')
  } catch (error: any) {
    console.error('=== HTTP请求失败 ===')
    console.error('错误详情:', error)
    if (error.response) {
      console.error('响应状态:', error.response.status)
      console.error('响应数据:', error.response.data)
    }
    showFailToast('提交订单失败，请检查网络连接')
  }
}

function testFormData() {
  console.log('=== 测试表单数据 ===')
  console.log('客户:', customer.value)
  console.log('负责人:', responsible.value) 
  console.log('商品项:', items.value)
  console.log('产品列表:', products.value)
  console.log('总价:', totalPrice.value)
  showSuccessToast('表单数据已输出到控制台')
}

// 订单列表（分页/搜索）
const orderKw = ref('')
const orders = ref<OrderListItem[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))

// 订单详情
const showOrderDetail = ref(false)
const currentOrder = ref<OrderListItem | null>(null)

async function viewOrderDetail(order: OrderListItem) {
  try {
    const { data } = await ordersApi.getDetail(order.ID)
    currentOrder.value = data
    showOrderDetail.value = true
  } catch (error) {
    showFailToast('获取订单详情失败')
  }
}

async function loadOrders() {
  try {
    const { data } = await ordersApi.getList({ page: page.value, pageSize: pageSize.value, customer: orderKw.value })
    orders.value = data.items || []
    total.value = data.total || 0
  } catch (e: any) {
    const msg = e?.response?.data?.error || e?.message || '加载订单失败'
    showFailToast(msg)
  }
}
function searchOrders() { page.value = 1; loadOrders() }
function prevPage() { if (page.value > 1) { page.value--; loadOrders() } }
function nextPage() { if (page.value < totalPages.value) { page.value++; loadOrders() } }
function changePageSize(ps: number) { pageSize.value = ps; page.value = 1; loadOrders() }

function formatDate(dateStr?: string) {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(async () => { await loadProducts(); await loadOrders() })
</script>

<template>
  <div class="page">
    <h2>销售开单</h2>

    <Form @submit.prevent="submitOrder">
      <CellGroup inset>
        <Field v-model.trim="customer" label="客户" placeholder="请输入客户名称" />
        <Field v-model.trim="responsible" label="负责人" placeholder="请输入负责人" />
      </CellGroup>

      <div class="table">
        <div class="t-head">
          <div class="col name">商品</div>
          <div class="col price">单价</div>
          <div class="col qty">数量</div>
          <div class="col amount">金额</div>
          <div class="col ops"></div>
        </div>
        <div class="t-row" v-for="(row, idx) in items" :key="idx">
          <div class="col name">
            <select v-model.number="row.productId" class="native-select">
              <option :value="undefined">请选择商品</option>
              <option v-for="p in products" :key="p.ID" :value="p.ID">{{ p.name }}（¥{{ p.price }}，库{{ p.stock }}）</option>
            </select>
          </div>
          <div class="col price">¥ {{ detailedItems[idx]?.price?.toFixed(2) }}</div>
          <div class="col qty"><input type="number" v-model.number="row.quantity" min="1" class="native-input" /></div>
          <div class="col amount">¥ {{ detailedItems[idx]?.amount?.toFixed(2) }}</div>
          <div class="col ops"><Button size="small" type="danger" plain @click="removeRow(idx)" :disabled="items.length === 1">删除</Button></div>
        </div>
        <div style="padding:8px 12px;"><Button size="small" @click="addRow">+ 添加一行</Button></div>
      </div>

      <div style="margin:12px 0; font-weight: bold;">合计：¥ {{ totalPrice.toFixed(2) }}</div>
      <div style="padding:0 12px 12px; display: flex; gap: 12px;">
        <Button type="primary" round block native-type="submit">提交订单</Button>
        <Button type="success" round block @click="submitOrder">直接提交</Button>
        <Button type="warning" round block @click="testFormData">测试数据</Button>
      </div>
    </Form>

    <h3 style="margin-top:16px;">订单列表</h3>
    <div class="filters">
      <Field v-model="orderKw" label="搜索" placeholder="按客户搜索" />
      <Button size="small" @click="searchOrders">搜索</Button>
    </div>

    <div class="table">
      <div class="t-head">
        <div class="col id">ID</div>
        <div class="col customer">客户</div>
        <div class="col responsible">负责人</div>
        <div class="col total">金额</div>
        <div class="col cnt">明细数</div>
        <div class="col time">创建时间</div>
        <div class="col ops">操作</div>
      </div>
      <div v-if="orders.length === 0" style="padding: 12px;">
        <Empty description="暂无数据" />
      </div>
      <div class="t-row" v-for="o in orders" :key="o.ID">
        <div class="col id">{{ o.ID }}</div>
        <div class="col customer">{{ o.customer }}</div>
        <div class="col responsible">{{ o.responsible || '-' }}</div>
        <div class="col total">¥ {{ (o.total_price || 0).toFixed(2) }}</div>
        <div class="col cnt">{{ o.items?.length || 0 }}</div>
        <div class="col time">{{ formatDate(o.CreatedAt) }}</div>
        <div class="col ops">
          <Button size="small" type="primary" @click="viewOrderDetail(o)">详情</Button>
        </div>
      </div>
    </div>

    <div class="pager">
      <Pagination :total-items="total" :items-per-page="pageSize" :show-page-size="0" v-model:current-page="page" @change="loadOrders" />
    </div>

    <!-- 订单详情弹窗 -->
    <Dialog v-model:show="showOrderDetail" title="订单详情" :show-cancel-button="false" confirm-button-text="关闭">
      <div v-if="currentOrder" class="order-detail">
        <div class="detail-section">
          <h4>基本信息</h4>
          <div class="detail-item">
            <span class="label">订单ID:</span>
            <span class="value">{{ currentOrder.ID }}</span>
          </div>
          <div class="detail-item">
            <span class="label">客户:</span>
            <span class="value">{{ currentOrder.customer }}</span>
          </div>
          <div class="detail-item">
            <span class="label">负责人:</span>
            <span class="value">{{ currentOrder.responsible || '-' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">订单金额:</span>
            <span class="value">¥ {{ (currentOrder.total_price || 0).toFixed(2) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">创建时间:</span>
            <span class="value">{{ formatDate(currentOrder.CreatedAt) }}</span>
          </div>
        </div>

        <div class="detail-section">
          <h4>商品明细</h4>
          <div class="items-table">
            <div class="items-head">
              <div class="col">商品名称</div>
              <div class="col">单价</div>
              <div class="col">数量</div>
              <div class="col">小计</div>
            </div>
            <div class="items-row" v-for="item in currentOrder.items" :key="item.ID">
              <div class="col">{{ item.product_name }}</div>
              <div class="col">¥ {{ item.price.toFixed(2) }}</div>
              <div class="col">{{ item.quantity }}</div>
              <div class="col">¥ {{ (item.price * item.quantity).toFixed(2) }}</div>
            </div>
          </div>
        </div>
      </div>
    </Dialog>
  </div>
</template>

<style scoped>
.page { padding-bottom: 16px; }
.table { border: 1px solid #eee; border-radius: 8px; overflow: hidden; margin: 12px 0; }
.t-head, .t-row { display: grid; grid-template-columns: 60px 1fr 1fr 100px 80px 140px 80px; }
.t-head { background: #fafafa; font-weight: 600; }
.col { padding: 10px 12px; border-bottom: 1px solid #eee; font-size: 14px; overflow: hidden; text-overflow: ellipsis; }
.native-select, .native-input { width: 100%; padding: 6px 8px; }
.filters { display: flex; gap: 8px; align-items: center; padding: 0 12px; }
.pager { display: flex; justify-content: center; padding: 12px; }

.order-detail { padding: 16px 0; }
.detail-section { margin-bottom: 20px; }
.detail-section h4 { margin: 0 0 12px 0; color: #323233; font-size: 16px; }
.detail-item { display: flex; padding: 8px 0; border-bottom: 1px solid #f5f5f5; }
.detail-item:last-child { border-bottom: none; }
.detail-item .label { width: 80px; color: #646566; }
.detail-item .value { flex: 1; color: #323233; }

.items-table { border: 1px solid #eee; border-radius: 6px; overflow: hidden; }
.items-head, .items-row { display: grid; grid-template-columns: 2fr 1fr 1fr 1fr; }
.items-head { background: #f7f8fa; font-weight: 600; }
.items-head .col, .items-row .col { padding: 12px 8px; border-bottom: 1px solid #eee; font-size: 14px; }
.items-row:last-child .col { border-bottom: none; }
</style>